package cn.enilu.flash.mobile.controller;

import cn.enilu.flash.bean.core.BussinessLog;
import cn.enilu.flash.bean.entity.release.TaskInfo;
import cn.enilu.flash.bean.entity.release.TaskOrder;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.service.release.TaskInfoService;
import cn.enilu.flash.service.release.TaskOrderService;
import cn.enilu.flash.web.controller.BaseController;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 领取刷单任务
 */
@RestController
@RequestMapping("/user/task_order")
public class TaskOrderController extends BaseController {

    @Autowired
    private TaskInfoService taskInfoService;

    @Autowired
    private TaskOrderService taskOrderService;

    /**
     * 领取刷单订单
     *
     * @param taskOrder
     * @return
     */
    @PostMapping("/add")
    @BussinessLog(value = "创建刷单任务")
    public Object addTaskOrder(@RequestBody TaskOrder taskOrder) {

        Long idUser = getIdUser();
        if (idUser == null) {
            return Rets.failure("用户信息不存在");
        }
        if (taskOrder.getTaskInfoId() == null) {
            return Rets.failure("任务信息不存在");
        }
        TaskInfo taskInfo = taskInfoService.get(taskOrder.getTaskInfoId());
        if (taskInfo == null) {
            return Rets.failure("任务不存在");
        }
        if (!taskInfo.getIsOnSale()) {
            return Rets.failure("该任务已结束");
        }
        if (taskInfo.getStock() - taskInfo.getSuccessCount() <= 0) {
            return Rets.failure("当前任务已完成");
        }
        if (DateUtil.compare(taskInfo.getBeginTime(), new Date()) > 0 || DateUtil.compare(taskInfo.getEndTime(), new Date()) < 0) {
            return Rets.failure("当前任务已过期");
        }
        boolean flag = taskOrderService.createTaskOrder(taskOrder, taskInfo, idUser);
        if (flag) {
            return Rets.success("任务领取成功");
        }
        return Rets.success();
    }
}
